import store from '@/store';
import { getCache } from '@/utils/session';

/**
 * 界面按钮权限控制
 */
const hasPermission = {
    install(Vue) {
        Vue.directive('permission', {
            inserted: (el, binding, vnode) => {
                filterGlobalPermission(el, binding, vnode);
            }
        });
    }
};
/**
 * 界面按钮权限控制
 */
export const filterGlobalPermission = (el, binding) => {
    const { value } = binding;
    const permissions = store.getters && store.getters.permissions;
    if (value && value instanceof Array && value.length > 0) {
        const permissionRules = value;
        const isPermission = permissions.some(permision => {
            return permissionRules.includes(permision);
        });
        if (!isPermission) {
            // el.parentNode && el.parentNode.removeChild(el)
            return false;
        }
    } else {
        throw new Error(`need permissions! Like v-permission="['edit','search']"`);
    }
};
export default hasPermission;

/***
 * 用来控制按钮的disabled属性
 */
export function hasBtnPermission(permission) {
    const permissions = store.getters && store.getters.permissions;
    if (permissions?.length == 0) {
        return true;
    }
    if (permission && permission instanceof Array && permission.length > 0) {
        const permissionRules = permission;
        const isPermission = permissions.some(item => {
            return permissionRules.includes(item);
        });
        if (!isPermission) {
            return true;
        }
    } else {
        // throw new Error(`need permissions`)
        return false;
    }
}

//是否有页面权限
export const hasPermPage = page => {
    const permisionRouters = getCache('routers');
    let findItem = findPage(permisionRouters, page);
    return findItem ? false : true;
};

const findPage = (data, page) => {
    let getItem = null;
    if (Array.isArray(data)) {
        data.map(item => {
            if (item.path == page || item.redirect == page) {
                getItem = item;
            }else{
                if (item.children && item.children.length) {
                    let getPage = findPage(item.children, page);
                    if(getPage){
                        getItem = getPage;
                    }
                }
            }
        });
    }
    return getItem;
};
